package com.heima.wemedia.service.impl;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.message.NewsAutoScanConstants;
import com.heima.common.message.NewsUpOrDownConstants;
import com.heima.common.message.PublishArticleConstants;
import com.heima.common.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    WmMaterialMapper wmMaterialMapper;
    @Autowired
    WmNewsMapper wmNewsMapper;
    @Autowired
    WmUserMapper wmUserMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 人工审核
     * @param status  2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        if (dto==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        //根据传入的id查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //更改状态
        wmNews.setStatus(status);
        wmNews.setReason("人工审核通过");
        //如果传入参数中含有驳回原因设置
        if (StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        //TODO 通知定时发布文章消息
        if (WemediaConstants.WM_NEWS_AUTH_PASS.equals(wmNews.getStatus())){
            long publishTime = wmNews.getPublishTime().getTime();
            long nowTime = System.currentTimeMillis();
            long remainTime = publishTime - nowTime;
            //发布文章
            rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                    , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                    , wmNews.getId(), new MessagePostProcessor() {
                        /**
                         * 消息的后置处理器，可以对消息属性进行设置
                         * @param message
                         * @return
                         * @throws AmqpException
                         */
                        @Override
                        public Message postProcessMessage(Message message) throws AmqpException {
                            // 设置 x-delay 延迟时间
                            message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                            return message;
                        }
                    });
            log.info("成功发送延时发布文章消息   文章id:{}  延迟时间: {}",wmNews.getId(),remainTime);
        }

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVO wmNewsVo = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());

        if(StringUtils.isNotBlank(dto.getTitle())){
            //  concat(%,?,%)
            dto.setTitle("%"+dto.getTitle()+"%");
        }

        //2.分页查询
        List<WmNewsVO> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.检查参数
        if(dto == null || dto.getId() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if(enable == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable)&&!WemediaConstants.WM_NEWS_DOWN.equals(enable))){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上下架状态错误");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态，
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
                .set(WmNews::getEnable,dto.getEnable()));
        //同步到app端（后期做）TODO
        if (WemediaConstants.WM_NEWS_UP.equals(enable)) {
            //发送上架消息
            rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                                          NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,
                                          wmNews.getArticleId()  );
            log.info("成功 发送文章上架的消息  消息内容 ：{}",wmNews.getArticleId());
        }else {
            //发送下架消息
            rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                                            NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,
                                            wmNews.getArticleId());
            log.info("成功 发送文章下架的消息  消息内容 ：{}",wmNews.getArticleId());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if(id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        //将dto封装成wmNews对象
        WmNews wmNews = getWmNews(dto);
        //保存或修改文章
        saveOrupdateWmNews(wmNews);
        //如果当前文章是草稿，不需要保存关联关系
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())){
            return ResponseResult.okResult();
        }

        //保存文章 和素材的关联关系

        //从文章内容中抽取出所有素材路径
        List<String> materiaUrls = parseContentImages(wmNews.getContent());

        //保存文章内容 所引用的素材 关联关系
        if (!CollectionUtils.isEmpty(materiaUrls)){
            saveRelativeInfo(materiaUrls,wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);
        }

        //保存封面所引用的素材 关联关系
        saveRelativeInfoForCover(dto,materiaUrls,wmNews);

        //TODO 给rabbitmq发送消息  自动审核文章消息
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送 待审核消息 ==> 队列:{}, 文章id:{}",NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());

        return ResponseResult.okResult();
    }

    /**
     * 保存封面和素材的关联关系
     *   如果 type=-1 需要根据内容素材  生成 封面列表
     * @param dto 前端传入的参数
     * @param materialUrls
     * @param wmNews
     */
    private void saveRelativeInfoForCover(WmNewsDTO dto, List<String> materialUrls, WmNews wmNews) {
        // 前端传递过来的封面列表
        List<String> images = dto.getImages();
        // 如果dto.getType == -1 需要自动生成封面
        if(WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            int size = materialUrls==null? 0 : materialUrls.size();
            if(size == 1){
                // 单图
                images = materialUrls.stream().limit(size).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }else if (size >= 2){
                // 多图
                images = materialUrls.stream().limit(size).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }else {
                // 无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            wmNews.setImages(imageListToStr(images));
            updateById(wmNews);
        }
        // 保存封面 和 素材关联关系
        if (!CollectionUtils.isEmpty(images)) {
            // 在替换一次前缀路径
            images = images.stream().map(url ->url.replaceAll(webSite,"")).collect(Collectors.toList());
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    /**
     * 保存文章内容 所引用的素材 关联关系
     * @param materiaUrls  素材路径集合
     * @param newsId  文章ID
     * @param type  引用类型(0素材 or 1封面)
     */
    private void saveRelativeInfo(List<String> materiaUrls, Integer newsId, Short type) {
        //先根据素材路径列表 和当前登录用户id 查询出素材id集合
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .in(WmMaterial::getUrl, materiaUrls)
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
                .select(WmMaterial::getId));
        // 2. 判断传入路径的数量 和  素材id的素材是否一致 ，如果不一致说明素材缺失
        if(wmMaterials.size()!=materiaUrls.size()){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材缺失，保存失败");
        }
        // 3. 将素材id 文章id 引用类型 插入到关联表中
        //TODO wmNewsMaterialMapper.saveRelations(materialIds,newsId,type);
        for (WmMaterial wmMaterial : wmMaterials) {
            // 批量保存关联关系
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(wmMaterial.getId());
            wmNewsMaterial.setNewsId(newsId);
            wmNewsMaterial.setType(type);
            wmNewsMaterialMapper.insert(wmNewsMaterial);
        }
    }

    /**
     * 从文章内容中抽取出所有素材路径
     * @param content
     * @return
     */
    private List<String> parseContentImages(String content) {
        List<Map> mapList = JSON.parseArray(content, Map.class);

        return mapList.stream()
                //过滤出素材路径
                .filter(m->WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(m.get("type")))
                //将路径转为字符串
                .map(m->String.valueOf(m.get("value")))
                //替换路径前缀
                .map(url->url.replaceAll(webSite,""))
                //去重复路径
                .distinct()
                .collect(Collectors.toList());
    }


    /**
     * 保存或修改文章
     * @param wmNews
     */
    private void saveOrupdateWmNews(WmNews wmNews) {
        if(wmNews.getId()==null){
            //没有文章Id就直接保存
            save(wmNews);
        }else {
            //有文章Id就代表修改
            //先删除文章和素材的关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);

        }
    }

    /**
     * 将dto封装成wmNews对象
     * @param dto
     * @return
     */
    private WmNews getWmNews(WmNewsDTO dto) {
        if (StringUtils.isBlank(dto.getContent())||StringUtils.isBlank(dto.getTitle())) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"文章内容或标题不能为空");
        }
        //判断是否登陆
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //保存或修改文章
        WmNews wmNews = new WmNews();
        //将传入dto参数设置进wmNews
        BeanUtils.copyProperties(dto,wmNews);
        //如果封面选择是自动，先将状态设置为null
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        //将封面集合转换成字符串并存入wmnews
        wmNews.setImages(imageListToStr(dto.getImages()));

        wmNews.setUserId(user.getId());

        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);//默认上架
        return wmNews;
    }

    /**
     * 图片列表转字符串，并去除图片前缀
     * @param images 图片列表
     * @param
     */
    private String imageListToStr(List<String> images) {
        if (CollectionUtils.isEmpty(images)){
            return null;
        }
        return images.stream().map(url -> url.replace(webSite, "")).collect(Collectors.joining(","));
    }

    /**
     * 查询所有自媒体文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //1 参数检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2 条件封装执行查询
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        // 文章标题模糊查询
        wrapper.like(StringUtils.isNotBlank(dto.getKeyword()),WmNews::getTitle, dto.getKeyword());
        // 频道id
        wrapper.eq(dto.getChannelId() != null,WmNews::getChannelId, dto.getChannelId());
        // 文章状态
        wrapper.eq(dto.getStatus() != null,WmNews::getStatus, dto.getStatus());
        // 发布时间 >= 开始时间
        wrapper.ge(dto.getBeginPubDate() != null,WmNews::getPublishTime, dto.getBeginPubDate());
        // 发布时间 <= 开始时间
        wrapper.le(dto.getEndPubDate()!=null,WmNews::getPublishTime, dto.getBeginPubDate());
        // 当前自媒体人文章
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        wrapper.eq(WmNews::getUserId, user.getId());
        // 按照创建日期倒序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        // 分页条件构建
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //3 执行查询
        IPage<WmNews> pageResult = page(page, wrapper);
        //4 返回封装查询结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        result.setData(pageResult.getRecords());
        // 处理文章图片
        result.setHost(webSite);
        return result;
    }
}